package com.wangp.mywrite.s_netty.netty.ch1;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @description: TODO
 * @author tooStronger
 * @date 2023/3/17
 */
public class HelloServer {

    public static void main(String[] args) {
        // 1. 启动器，负责组装netty 组件，启动服务器
        new ServerBootstrap()
                // 2. BossEventLoopGroup，WorkerEventLoop(selector,thread)
                .group(new NioEventLoopGroup())
                // 3. 选择服务器的ServerSocketChannel
                .channel(NioServerSocketChannel.class)
                // 4. boss 服务建立连接，worker负责（child）负责读写，决定了worker(child)能执行哪些操作
                .childHandler(
                        // 5. 代码和客户端数据读写的通道 initializer 初始化，负责添加别的 handler
                        new ChannelInitializer<NioSocketChannel>() {
                            @Override
                            protected void initChannel(NioSocketChannel nsc) throws Exception {
                                // 6. 添加具体的handler
                                nsc.pipeline().addLast(new StringDecoder()); // 将 byteBuf 转成字符串
                                nsc.pipeline().addLast(new ChannelInboundHandlerAdapter() { // 自定义 handler
                                    // 读事件
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        System.out.println(msg);
                                    }
                                });
                            }
                        })
                // 7. 绑定监听端口
                .bind(8080);

    }
}
